package com.lmx.persistence.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.Role;
import com.lmx.repoDomain.tmodel.RolePrivilege;
import com.lmx.repoDomain.tmodel.Tenant;

@Service(value = "rolePrivilegeService")
public class RolePrivilegeServiceImpl extends BaseCrudServiceImpl<RolePrivilege> implements RolePrivilegeService {

	@Autowired
	private RoleService<Role> roleSrv;
	@Autowired
	private GenericService<Role> dslSrv;

	@Override
	@Transactional
	public void allocatePublicPrivilege(Tenant tenant) {
		Role publicRole = this.roleSrv.findPublicByTenant(tenant.getId());
		if (publicRole == null) {
			publicRole = new Role();
			publicRole.setCode(CommonConstants.ROLE_CODE.WECHAT.getCode());
			publicRole.setRemark("系统自动生成");
			publicRole.setTenant(tenant);
			publicRole.setName(CommonConstants.ROLE_CODE.WECHAT.getName());
			dslSrv.setEntityClass(Role.class);
			publicRole = (Role) dslSrv.create(publicRole);
		}
		StringBuilder sqlSb = new StringBuilder("delete from RolePrivilege where role.id = :roleId");
		super.em.createQuery(sqlSb.toString()).setParameter("roleId", publicRole.getId()).executeUpdate();
		sqlSb = new StringBuilder(
				"insert into t_s_role_function (function_id,role_id) (select fun.id ,:roleId from t_s_function as fun where (fun.functiontype= 21 or fun.functiontype= 23) and (fun.del_status = 0))");
		super.em.createNativeQuery(sqlSb.toString()).setParameter("roleId", publicRole.getId()).executeUpdate();
	}

}
